package com.yonyou.cyxdms.sysAuth.service.controller;


import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.service.auth.UserAuthService;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.MessageFormat;
import java.util.Map;


/**
 * @description: 根据jwt去外系统认证
 * @author: lijun
 * @create: 2019-10-29 11:26:31
 **/
@Api(tags = "认证相关接口")
@ApiIgnore
@RestController
@RequestMapping("/userAuth")
public class AuthController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String AUTH_USERINFO_KEY = "sysmanage:userInfo:";

    @Autowired
    SystemParamService systemParamService;

    @Autowired
    UserAuthService userAuthService;

    @Autowired
    UserController userController;

    @Autowired
    private RedisClient redis;

    /**
     * PostersTemplateController
     * 根据jwt去外系统认证
     *
     * @param paramMap paramMap 对象
     * @param headMap  headMap 对象
     * @return Map<String       ,               Object> 数据对应的map 结构
     * @author zhangxianchao
     * @since 2018-09-13
     */
    @GetMapping(value = "/auth")
    public LoginInfoDto getUserInfoByUserCode(@RequestParam Map<String, String> paramMap,
                                              @RequestHeader Map<String, String> headMap) {
        logger.debug("子系统认证开始-------------------------");
        String appId = headMap.get(UserAuthConstant.APP_SOURCE_CODE);
        String jwt = headMap.get(UserAuthConstant.TOKEN_NAME);
        String userAgent = headMap.get(UserAuthConstant.USER_AGENT);
        if (appId == null) {
            appId = paramMap.get(UserAuthConstant.APP_SOURCE_CODE);
        }
        if (appId == null) {
            appId = paramMap.get(UserAuthConstant.APP_SOURCE_CODE.toLowerCase());
        }
        if (appId == null) {
            appId = headMap.get(UserAuthConstant.APP_SOURCE_CODE.toLowerCase());
        }

        if (appId == null) {
            appId = headMap.get(UserAuthConstant.APP_SOURCE_CODE.toLowerCase());
        }

        if (jwt == null) {
            jwt = paramMap.get(UserAuthConstant.TOKEN_NAME);
        }

        if (StringUtils.isNullOrEmpty(userAgent) || "pc".equals(userAgent) || userAgent.equals(String.valueOf(SysAuthDictCodeConstants.STATUS_IS_YES))) {
            userAgent = String.valueOf(SysAuthDictCodeConstants.STATUS_IS_YES);
        } else {
            userAgent = String.valueOf(SysAuthDictCodeConstants.STATUS_IS_NOT);
        }

        logger.debug("token:{},appId:{},userAgent{}", jwt, appId, userAgent);

        return getLoginInfoDto(appId, jwt, userAgent, paramMap, headMap);
    }

    private LoginInfoDto getLoginInfoDto(String appId, String jwt, String userAgent, Map<String, String> paramMap,
                                         Map<String, String> headMap) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.LOGIN_CACHE_USERID, userAgent);
        String url = systemParamService.getParamValueByCode(UserAuthConstant.AUTH, appId);
        if (StringUtils.isBlank(url)) {
            logger.debug("未查询到url，按照原有的子系统认证方式认证。");
            LoginInfoDto userInfoByUserCode = userController.getUserInfoByUserCode(paramMap, headMap);
            return userInfoByUserCode;
        }
        logger.debug("查询到子系统认证url：{},调用主系统接口认证jwt", url);
        // 根据具体的实现获取用户信息
        LoginInfoDto dto = userAuthService.getAppUserInfo(appId, jwt, url, userAgent);
        logger.debug("------------------返回dto:{}", JSONUtil.objectToJson(dto));
        if (dto != null && dto.getUserId() != null) {
            // 子系统认证已经通过，这时候缓存jwt
            String subSysJwt = MessageFormat.format(SysAuthCommonConstants.SUB_JWT, appId, dto.getUserId());
            redis.set(subSysJwt, jwt, SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);
            logger.debug("子系统认证通过，登陆信息：{}，\n缓存jwt:key-->{},value-->:{}", dto, subSysJwt, redis.get(subSysJwt));
        }
        return dto;
    }
}
